package com.zx._02_thread.线程池;

import com.zx.common.util.ThreadUtil;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FutrueDemo {

    /**
     * Futrue 接口如下
     * // 取消任务
     * boolean cancel(boolean mayInterruptIfRunning);
     *
     * // 获取任务执行结果
     * V get() throws InterruptedException, ExecutionException;
     *
     * // 获取任务执行结果，带有超时时间限制
     * V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
     *
     * // 判断任务是否已经取消
     * boolean isCancelled();
     *
     * // 判断任务是否已经结束
     * boolean isDone();
     */
    public static void main(final String[] args) {
        final ExecutorService pool = Executors.newFixedThreadPool(10);

        final Future<String> resultFuture = pool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println("begin");
                ThreadUtil.sleep(1);
                System.out.println("end");
                return null;
            }
        });

        log.info("提交任务");
        // 通过阻塞主线程的方式获得任务的返回值
        //test1(resultFuture);
        //test2(resultFuture);
        //test3(resultFuture);
        test4(resultFuture);

        log.info("future是否关闭={}", resultFuture.isCancelled());
        log.info("任务结束");
        pool.shutdown();
    }

    /**
     * @param future
     * @Title: 简单操作
     * @date: 2020-7-2121:27:36
     * @author: zhangxue
     */
    public static void test1(final Future<String> future) {
        try {
            final String result = future.get();
            log.info(result);
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param future
     * @Title: 等待固定时长      超时会报异常
     * @date: 2020-7-2121:27:36
     * @author: zhangxue
     */
    public static void test2(final Future<String> future) {
        try {
            final String result = future.get(500, TimeUnit.MILLISECONDS);
            log.info(result);
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param future
     * @Title: 判断状态
     * @date: 2020-7-2121:27:36
     * @author: zhangxue
     */
    public static void test3(final Future<String> future) {
        while (!future.isDone()) {
            ThreadUtil.sleepMill(100L);
            log.info("任务未完成");
        }
        // 完成后，调用结果
        test1(future);
    }

    /**
     * @param future
     * @Title: 手动关闭任务, 其实也就是中断线程的阻塞状态
     * @date: 2020-7-2121:27:36
     * @author: zhangxue
     */
    public static void test4(final Future<String> future) {
        ThreadUtil.sleepMill(500L);
        // 手动关闭任务
        future.cancel(true);
        // 完成后，调用结果
        test1(future);//调用get会抛出异常
    }

}
